package blake3

import (
	"crypto/rand"
	"github.com/zeebo/blake3"
	"io"
	"os"
)

// Blake3Tool 是一个封装了blake3哈希算法的工具类
type Blake3Tool struct{}

// Hash 计算输入数据的blake3哈希值
func (b *Blake3Tool) Hash(data []byte) []byte {
	hasher := blake3.New()
	hasher.Write(data)
	return hasher.Sum(nil)
}

// HashReader 计算输入io.Reader的blake3哈希值
func (b *Blake3Tool) HashReader(reader io.Reader) ([]byte, error) {
	hasher := blake3.New()
	if _, err := io.Copy(hasher, reader); err != nil {
		return nil, err
	}
	return hasher.Sum(nil), nil
}

// HashFile 计算输入文件的blake3哈希值
func (b *Blake3Tool) HashFile(filePath string) ([]byte, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	return b.HashReader(file)
}

// GenerateKey 生成指定长度的随机blake3密钥
func (b *Blake3Tool) GenerateKey(keyLen int) ([]byte, error) {
	key := make([]byte, keyLen)
	if _, err := rand.Read(key); err != nil {
		return nil, err
	}
	return key, nil
}
